package com.ContactsWitch.jackiez;

import java.util.ArrayList;
import android.app.Activity;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.RawContacts;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import com.ContactsWitch.jackiez.util.LogUtil;

public class Importer extends Activity{
	public void ImportContacts(SQLiteDatabase db,ContentResolver cr) {
    	ArrayList<ContentProviderOperation> ops;
    	int rawContactInsertIndex;
	    Cursor cursor1 = db.rawQuery("SELECT data,raw_contacts_id FROM mycontacts WHERE my_mimetype='1' ", null);
	    Cursor cursor2; 
		LogUtil.LogShow("[import]", "321", LogUtil.DEBUG);

		while (cursor1.moveToNext()) {
			ContactInfo cci = new ContactInfo();
			//取得联系人名字
			cci.contactName = cursor1.getString(0);
			cci.contactrawid = cursor1.getInt(1);
			LogUtil.LogShow("[import]", cci.contactName, LogUtil.DEBUG);
	    	ops = new ArrayList();
	    	rawContactInsertIndex = ops.size(); 
	    	ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
	    			.withValue(RawContacts.ACCOUNT_TYPE,null)
	    			.withValue(RawContacts.ACCOUNT_NAME,null)
	    			.build());
	    	ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
	    			.withValueBackReference(Data.RAW_CONTACT_ID,rawContactInsertIndex)
	    			.withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
	    			.withValue(StructuredName.DISPLAY_NAME, cci.contactName)
	    			.build());
			cursor2 = db.rawQuery("SELECT data FROM mycontacts WHERE my_mimetype='2' AND raw_contacts_id="+cci.contactrawid, null);
			while(cursor2.moveToNext()){
				cci.userNumber = cursor2.getString(0);
		    	ops.add(ContentProviderOperation.newInsert(
		    		    Data.CONTENT_URI)
		    		    .withValueBackReference(Data.RAW_CONTACT_ID,rawContactInsertIndex)
		    		    .withValue(Data.MIMETYPE,Phone.CONTENT_ITEM_TYPE)
		    		    .withValue(Phone.NUMBER,cci.userNumber)
		    		    .withValue(Phone.TYPE, Phone.TYPE_MOBILE)
		    		    .build());
				LogUtil.LogShow("[import]", cci.userNumber, LogUtil.DEBUG);
			}
			
	    	try {
				cr.applyBatch(ContactsContract.AUTHORITY, ops);
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (OperationApplicationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 

		}
	}
}